package dao

import (
	"fmt"
	"time"

	"openeuler.org/PilotGo/PilotGo-plugin-automation/internal/global"
	"openeuler.org/PilotGo/PilotGo-plugin-automation/internal/module/job_history/model"

	jobstatus "openeuler.org/PilotGo/PilotGo-plugin-automation/internal/module/common/enum/job"
)

func GetJobResult(jobId string) (*model.Job, error) {
	var job model.Job
	if err := global.App.MySQL.Model(&model.Job{}).Where("job_id = ?", jobId).First(&job).Error; err != nil {
		return nil, err
	}
	return &job, nil
}

func UpdateJobResult(jobId, jobStatusCode string, startTime, endTime int64, totalTime string) error {
	updateJobData := map[string]interface{}{
		"exec_code":  jobStatusCode,
		"job_status": jobstatus.GetJobStatusByCode(jobStatusCode),
		"start_time": startTime,
		"end_time":   endTime,
		"total_time": totalTime,
	}

	if err := global.App.MySQL.Model(&model.Job{}).Where("job_id = ?", jobId).Updates(updateJobData).Error; err != nil {
		return fmt.Errorf("更新父作业状态失败: %v", err)
	}

	return nil
}

func calculateTotalTime(startTime, endTime int64) string {
	if startTime <= 0 || endTime <= 0 {
		return ""
	}

	durationMillis := endTime - startTime
	if durationMillis <= 0 {
		return ""
	}

	// 直接将毫秒转换为time.Duration
	duration := time.Duration(durationMillis) * time.Millisecond

	// 按照不同的时间范围返回不同格式
	switch {
	case durationMillis < 1000: // 小于1秒
		if durationMillis < 100 {
			return fmt.Sprintf("%d毫秒", durationMillis)
		}
		// 显示小数秒
		seconds := float64(durationMillis) / 1000.0
		return fmt.Sprintf("%.2f秒", seconds)

	case durationMillis < 60000: // 小于1分钟
		seconds := int(duration.Seconds())
		millis := durationMillis % 1000
		if millis > 0 {
			return fmt.Sprintf("%d.%d秒", seconds, millis/100) // 保留1位小数
		}
		return fmt.Sprintf("%d秒", seconds)

	case durationMillis < 3600000: // 小于1小时
		minutes := int(duration.Minutes())
		seconds := int(duration.Seconds()) % 60
		if seconds > 0 {
			return fmt.Sprintf("%d分%d秒", minutes, seconds)
		}
		return fmt.Sprintf("%d分钟", minutes)

	case durationMillis < 86400000: // 小于1天
		hours := int(duration.Hours())
		minutes := int(duration.Minutes()) % 60
		seconds := int(duration.Seconds()) % 60

		if minutes == 0 && seconds == 0 {
			return fmt.Sprintf("%d小时", hours)
		} else if seconds == 0 {
			return fmt.Sprintf("%d小时%d分钟", hours, minutes)
		}
		return fmt.Sprintf("%d小时%d分%d秒", hours, minutes, seconds)

	default: // 大于等于1天
		days := int(duration.Hours() / 24)
		hours := int(duration.Hours()) % 24
		minutes := int(duration.Minutes()) % 60

		if hours == 0 && minutes == 0 {
			return fmt.Sprintf("%d天", days)
		} else if minutes == 0 {
			return fmt.Sprintf("%d天%d小时", days, hours)
		}
		return fmt.Sprintf("%d天%d小时%d分钟", days, hours, minutes)
	}
}
